<template>
  <div class="page-container">

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showAddRecordDialog">
        <el-icon><Plus /></el-icon>记录运动
      </el-button>
      <el-button type="info" @click="showHistoryDialog">
        <el-icon><Clock /></el-icon>运动历史
      </el-button>
    </div>

    <!-- 运动统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <div class="health-card">
          <div class="card-header">
            <h3>运动统计</h3>
            <div class="header-actions">
              <el-radio-group v-model="chartPeriod" @change="loadChartData">
                <el-radio-button label="week">最近一周</el-radio-button>
                <el-radio-button label="month">最近一月</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-container" ref="chartContainer"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 今日运动量汇总 -->
    <el-row :gutter="20" class="summary-row">
      <el-col :span="24">
        <div class="health-card">
          <div class="card-header">
            <h3>今日运动量汇总</h3>
            <el-button type="primary" size="small" @click="refreshTodaySummary">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总运动时长</div>
                <div class="summary-value">{{ todaySummary.totalDuration }} 分钟</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.durationPercentage"
                    :color="getProgressColor(todaySummary.durationPercentage)"
                  />
                </div>
              </div>
            </el-col>

            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总消耗热量</div>
                <div class="summary-value">{{ todaySummary.totalCalories }} kcal</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.caloriesPercentage"
                    :color="getProgressColor(todaySummary.caloriesPercentage)"
                  />
                </div>
              </div>
            </el-col>

            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">运动次数</div>
                <div class="summary-value">{{ todaySummary.totalCount }} 次</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.countPercentage"
                    :color="getProgressColor(todaySummary.countPercentage)"
                  />
                </div>
              </div>
            </el-col>

            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">平均运动时长</div>
                <div class="summary-value">{{ todaySummary.averageDuration }} 分钟</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.averagePercentage"
                    :color="getProgressColor(todaySummary.averagePercentage)"
                  />
                </div>
              </div>
            </el-col>
          </el-row>

          <div class="recommendation">
            <p>
              建议每日运动：时长 30-60 分钟 | 消耗热量 200-500 kcal | 运动次数 1-3 次 |
              平均时长 20-30 分钟/次
            </p>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 运动记录弹窗 -->
    <el-dialog
      v-model="addRecordDialogVisible"
      title="记录运动"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="exerciseFormRef"
        :model="exerciseForm"
        :rules="exerciseRules"
        label-width="100px"
        class="exercise-form"
      >
        <el-form-item label="记录日期" prop="exerciseDate">
          <el-date-picker
            v-model="exerciseForm.exerciseDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disableFutureDate"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="运动类型" prop="exerciseType">
          <el-select
            v-model="exerciseForm.exerciseType"
            placeholder="请选择运动类型"
            style="width: 100%"
            @change="onExerciseTypeChange"
          >
            <el-option
              v-for="type in exerciseTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="运动时长" prop="duration">
          <el-input-number
            v-model="exerciseForm.duration"
            :min="1"
            :max="600"
            :step="5"
            placeholder="请输入运动时长(分钟)"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="消耗热量" prop="calorieConsume">
          <el-input-number
            v-model="exerciseForm.calorieConsume"
            :min="0"
            :max="2000"
            :step="10"
            placeholder="请输入消耗热量(kcal)"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="运动强度" prop="exerciseIntensity">
          <el-select
            v-model="exerciseForm.exerciseIntensity"
            placeholder="请选择运动强度"
            style="width: 100%"
          >
            <el-option label="低强度" value=1 />
            <el-option label="中等强度" value=2 />
            <el-option label="高强度" value=3 />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="exerciseForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addRecordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitExerciseForm" :loading="submitting">
            保存记录
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 运动历史记录弹窗 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="运动历史记录"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="history-header">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="loadHistoryRecords"
          style="margin-right: 10px"
        />
        <el-button type="primary" @click="loadHistoryRecords">
          <el-icon><Search /></el-icon>查询
        </el-button>
      </div>

      <el-table
        :data="historyRecords"
        style="width: 100%"
        v-loading="loading"
        height="400"
      >
        <el-table-column label="日期" width="120">
          <template #default="scope">
            {{ scope.row.exerciseDate || scope.row.recordDate }}
          </template>
        </el-table-column>
        <el-table-column prop="exerciseType" label="类型" width="100" />
        <el-table-column prop="duration" label="时长(分钟)" width="100" />
        <el-table-column prop="calorieConsume" label="消耗热量(kcal)" width="120" />
        <el-table-column label="强度" width="90">
          <template #default="scope">
            {{ scope.row.exerciseIntensity === 1 ? '低强度' : (scope.row.exerciseIntensity === 2 ? '中等强度' : '高强度') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="deleteRecord(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Clock, Refresh } from '@element-plus/icons-vue'
import { useExerciseStore } from '@/store/exercise'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

const exerciseStore = useExerciseStore()

const exerciseFormRef = ref()
const exerciseForm = ref({
  exerciseDate: dayjs().format('YYYY-MM-DD'),
  exerciseType: '',
  exerciseName: '',
  duration: null,
  calorieConsume: null,
  exerciseIntensity: '',
  notes: ''
})

const exerciseRules = {
  exerciseDate: [
    { required: true, message: '请选择记录日期', trigger: 'change' }
  ],
  exerciseType: [
    { required: true, message: '请选择运动类型', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入运动时长', trigger: 'blur' }
  ],
  exerciseIntensity: [
    { required: true, message: '请选择运动强度', trigger: 'change' }
  ]
}

const exerciseTypes = [
  { label: '跑步', value: '跑步' },
  { label: '游泳', value: '游泳' },
  { label: '骑行', value: '骑行' },
  { label: '健身', value: '健身' },
  { label: '瑜伽', value: '瑜伽' },
  { label: '球类运动', value: '球类运动' },
  { label: '其他', value: '其他' }
]

const dateRange = ref([
  dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
  dayjs().format('YYYY-MM-DD')
])

const historyRecords = ref([])
const loading = ref(false)
const submitting = ref(false)
const chartPeriod = ref('week')
const chartContainer = ref()
let chartInstance = null

// 弹窗显示状态
const addRecordDialogVisible = ref(false)
const historyDialogVisible = ref(false)

// 今日运动量汇总数据
const todaySummary = ref({
  totalDuration: 0,
  totalCalories: 0,
  totalCount: 0,
  averageDuration: 0,
  durationPercentage: 0,
  caloriesPercentage: 0,
  countPercentage: 0,
  averagePercentage: 0
})

// 方法
const disableFutureDate = (time) => {
  return time.getTime() > Date.now()
}

const onExerciseTypeChange = (value) => {
  // 根据运动类型自动填充运动名称
  if (value !== '其他') {
    exerciseForm.value.exerciseName = value
  }
}

const showAddRecordDialog = () => {
  resetForm()
  addRecordDialogVisible.value = true
}

const showHistoryDialog = () => {
  // 设置默认日期范围为最近7天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(endDate.getDate() - 7)
  
  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]
  
  loadHistoryRecords()
  historyDialogVisible.value = true
}

const submitExerciseForm = async () => {
  if (!exerciseFormRef.value) return
  
  await exerciseFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await exerciseStore.createRecord(exerciseForm.value)
        ElMessage.success('运动记录保存成功')
        addRecordDialogVisible.value = false
        resetForm()
        loadHistoryRecords()
        loadChartData()
        refreshTodaySummary()
      } catch (error) {
        console.error('保存运动记录失败', error)
        ElMessage.error('保存失败，请重试')
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  if (exerciseFormRef.value) {
    exerciseFormRef.value.resetFields()
  }
  exerciseForm.value = {
    exerciseDate: dayjs().format('YYYY-MM-DD'),
    exerciseType: '',
    exerciseName: '',
    duration: null,
    calorieConsume: null,
    exerciseIntensity: '',
    notes: ''
  }
}

const loadHistoryRecords = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) return
  
  loading.value = true
  try {
    const [startDate, endDate] = dateRange.value
    const response = await exerciseStore.getRecordsByDateRange(startDate, endDate)
    historyRecords.value = response || []
  } catch (error) {
    console.error('加载运动历史记录失败', error)
    ElMessage.error('加载历史记录失败')
  } finally {
    loading.value = false
  }
}

const deleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await exerciseStore.deleteRecord(record.recordId)
    ElMessage.success('删除成功')
    loadHistoryRecords()
    loadChartData()
    refreshTodaySummary()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除记录失败', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const loadChartData = async () => {
  try {
    let startDate, endDate
    
    if (chartPeriod.value === 'week') {
      startDate = dayjs().subtract(7, 'day').format('YYYY-MM-DD')
      endDate = dayjs().format('YYYY-MM-DD')
    } else {
      startDate = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
      endDate = dayjs().format('YYYY-MM-DD')
    }
    
    const response = await exerciseStore.getRecordsByDateRange(startDate, endDate)
    const records = response || []
    
    // 按日期分组统计
    const dateMap = {}
    records.forEach(record => {
      // 使用正确的字段名 exerciseDate 而不是 recordDate
      const recordDate = record.exerciseDate || record.recordDate;
      if (!dateMap[recordDate]) {
        dateMap[recordDate] = {
          duration: 0,
          calorieConsume: 0,
          count: 0
        }
      }
      dateMap[recordDate].duration += record.duration || 0
      dateMap[recordDate].calorieConsume += record.calorieConsume || 0
      dateMap[recordDate].count += 1
    })
    
    // 准备图表数据
    const dates = Object.keys(dateMap).sort()
    const durationData = dates.map(date => dateMap[date].duration)
    const calorieData = dates.map(date => dateMap[date].calorieConsume)
    
    // 渲染图表
    renderChart(dates, durationData, calorieData)
  } catch (error) {
    console.error('加载图表数据失败', error)
  }
}

const renderChart = (dates, durationData, calorieData) => {
  if (!chartContainer.value) return
  
  nextTick(() => {
    if (chartInstance) {
      chartInstance.dispose()
    }
    
    chartInstance = echarts.init(chartContainer.value)
    
    const option = {
      title: {
        text: '运动统计趋势'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['运动时长(分钟)', '消耗热量(kcal)']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates
      },
      yAxis: [
        {
          type: 'value',
          name: '时长(分钟)',
          position: 'left'
        },
        {
          type: 'value',
          name: '热量(kcal)',
          position: 'right'
        }
      ],
      series: [
        {
          name: '运动时长(分钟)',
          type: 'line',
          yAxisIndex: 0,
          data: durationData,
          smooth: true
        },
        {
          name: '消耗热量(kcal)',
          type: 'line',
          yAxisIndex: 1,
          data: calorieData,
          smooth: true
        }
      ]
    }
    
    chartInstance.setOption(option)
    
    // 响应式调整
    window.addEventListener('resize', () => {
      chartInstance.resize()
    })
  })
}

const refreshTodaySummary = async () => {
  try {
    const today = dayjs().format('YYYY-MM-DD')
    const response = await exerciseStore.getRecords(today)
    const records = response || []
    
    // 计算今日运动总量
    let totalDuration = 0
    let totalCalories = 0
    let totalCount = 0
    
    records.forEach(record => {
      totalDuration += record.duration || 0
      totalCalories += record.calorieConsume || 0
      totalCount += 1
    })
    
    // 计算平均运动时长
    const averageDuration = totalCount > 0 ? Math.round(totalDuration / totalCount) : 0
    
    // 计算百分比（基于推荐运动量）
    const durationPercentage = Math.min(Math.round((totalDuration / 45) * 100), 100)
    const caloriesPercentage = Math.min(Math.round((totalCalories / 350) * 100), 100)
    const countPercentage = Math.min(Math.round((totalCount / 2) * 100), 100)
    const averagePercentage = Math.min(Math.round((averageDuration / 25) * 100), 100)
    
    todaySummary.value = {
      totalDuration,
      totalCalories,
      totalCount,
      averageDuration,
      durationPercentage,
      caloriesPercentage,
      countPercentage,
      averagePercentage
    }
  } catch (error) {
    console.error('获取今日运动量汇总失败', error)
  }
}

const getProgressColor = (percentage) => {
  if (percentage < 70) return '#67c23a'
  if (percentage < 90) return '#e6a23c'
  return '#f56c6c'
}

// 初始化
onMounted(() => {
  loadChartData()
  refreshTodaySummary()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #2c3e50;
  font-weight: 600;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.chart-row,
.summary-row {
  margin-top: 20px;
}

.health-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.history-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.exercise-form {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.summary-item {
  text-align: center;
  padding: 10px;
}

.summary-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.summary-progress {
  margin-bottom: 5px;
}

.recommendation {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  text-align: center;
  color: #606266;
  font-size: 14px;
}
</style>